package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Api(tags = "通用接口")
@RequestMapping("/admin/common")
@RestController
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 使用阿里OSS上传文件
     * @param file
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();//获取文件原始名
        log.info("文件上传文件原始名：{}",originalFilename);
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));//获取文件后缀 .jpg
        String url =null;
        try {
            //调用AliOSSUtil工具类的upload方法上传文件
            String objectName = UUID.randomUUID().toString()+suffix;
            url=aliOssUtil.upload(file.getBytes(),objectName);
        } catch (IOException e) {
            log.info("文件上传失败{}",e.getMessage());
            return Result.error("文件上传失败");
        }
        //返回文件上传到阿里云OSS上的url
        return Result.success(url);
    }
}
